<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Cache-Control" content="public, max-age=1800">
    <meta name="theme-color" content="#667eea">
    <title>客户数据管理 - 数据收集系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css" rel="stylesheet" media="print" onload="this.media='all'">
    <link href="../styles/optimized.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js" defer></script>
    <script src="../js/api-cache.js" defer></script>
    <noscript>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css" rel="stylesheet">
    </noscript>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        .navbar {
            background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 50%, #90caf9 100%) !important;
            box-shadow: 0 4px 25px rgba(33, 150, 243, 0.15);
            border: none;
            padding: 1.5rem 0;
            backdrop-filter: blur(20px);
            border-bottom: 1px solid rgba(33, 150, 243, 0.2);
            position: relative;
            min-height: 100px;
        }
        
        .navbar::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, #2196f3 0%, #1976d2 50%, #2196f3 100%);
        }

        .navbar-brand {
            font-weight: 700;
            font-size: 1.8rem;
            color: #1565c0 !important;
            text-decoration: none;
            display: flex;
            align-items: center;
        }

        .navbar-brand i {
            margin-right: 12px;
            font-size: 1.6rem;
            color: #1565c0;
        }

        .btn-outline-light {
            border: 2px solid #1976d2;
            background: linear-gradient(135deg, #2196f3 0%, #1976d2 100%);
            color: #ffffff !important;
            font-weight: 700;
            padding: 0.8rem 1.5rem;
            border-radius: 20px;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            text-transform: uppercase;
            letter-spacing: 0.5px;
            font-size: 0.8rem;
            position: relative;
            overflow: hidden;
            box-shadow: 0 6px 20px rgba(33, 150, 243, 0.3);
            backdrop-filter: blur(10px);
        }

        .btn-outline-light:hover {
            background: linear-gradient(135deg, #1976d2 0%, #1565c0 100%) !important;
            color: #ffffff !important;
            border-color: #1565c0;
            transform: translateY(-2px) scale(1.02);
            box-shadow: 0 10px 30px rgba(33, 150, 243, 0.4);
        }

        .btn-outline-info {
            background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);
            border: none;
            color: white !important;
            font-weight: 600;
            padding: 0.6rem 1.2rem;
            border-radius: 15px;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(23, 162, 184, 0.3);
        }

        .btn-outline-info:hover {
            background: linear-gradient(135deg, #138496 0%, #117a8b 100%);
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(23, 162, 184, 0.4);
        }

        .btn-outline-primary {
            background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
            border: none;
            color: white !important;
            font-weight: 600;
            padding: 0.6rem 1.2rem;
            border-radius: 15px;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(0, 123, 255, 0.3);
        }

        .btn-outline-primary:hover {
            background: linear-gradient(135deg, #0056b3 0%, #004085 100%);
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 123, 255, 0.4);
        }

        .btn-outline-danger {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
            border: none;
            color: white !important;
            font-weight: 600;
            padding: 0.6rem 1.2rem;
            border-radius: 15px;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(220, 53, 69, 0.3);
        }

        .btn-outline-danger:hover {
            background: linear-gradient(135deg, #c82333 0%, #bd2130 100%);
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(220, 53, 69, 0.4);
        }

        .btn-outline-secondary {
            background: linear-gradient(135deg, #6c757d 0%, #5a6268 100%);
            border: none;
            color: white !important;
            font-weight: 600;
            padding: 0.75rem 1.5rem;
            border-radius: 15px;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(108, 117, 125, 0.3);
        }

        .btn-outline-secondary:hover {
            background: linear-gradient(135deg, #5a6268 0%, #545b62 100%);
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(108, 117, 125, 0.4);
        }

        .container {
            margin-top: 0;
            padding-top: 40px;
            max-width: 1400px;
        }
        
        .header {
            background: white;
            padding: 30px;
            border-radius: 20px;
            box-shadow: 0 8px 30px rgba(0,0,0,0.1);
            margin-bottom: 30px;
            border: 1px solid rgba(33, 150, 243, 0.1);
        }
        
        .header h2 {
            color: #2c3e50;
            font-weight: 700;
            font-size: 2.2rem;
            margin-bottom: 0.5rem;
            display: flex;
            align-items: center;
        }
        
        .header h2 i {
            margin-right: 15px;
            color: #3498db;
            font-size: 2rem;
        }
        
        .header .text-muted {
            font-size: 1.1rem;
            color: #6c757d !important;
            font-weight: 400;
            margin-bottom: 0;
        }

        .filter-card {
            background: white;
            border: none;
            border-radius: 20px;
            box-shadow: 0 8px 30px rgba(0,0,0,0.1);
            margin-bottom: 30px;
            border: 1px solid rgba(33, 150, 243, 0.1);
            overflow: hidden;
        }

        .filter-card .card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 20px 30px;
            font-weight: 600;
            font-size: 1.1rem;
        }

        .filter-card .card-body {
            padding: 30px;
        }

        .form-label {
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 8px;
            font-size: 0.95rem;
        }

        .form-select {
            border: 2px solid #e9ecef;
            border-radius: 12px;
            padding: 12px 16px;
            font-size: 0.95rem;
            transition: all 0.3s ease;
            background-color: #f8f9fa;
        }

        .form-select:focus {
            border-color: #3498db;
            box-shadow: 0 0 0 0.2rem rgba(52, 152, 219, 0.25);
            background-color: white;
        }

        .data-card {
            background: white;
            border: none;
            border-radius: 20px;
            box-shadow: 0 8px 30px rgba(0,0,0,0.1);
            border: 1px solid rgba(33, 150, 243, 0.1);
            overflow: hidden;
        }

        .table {
            margin-bottom: 0;
        }

        .table th {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            font-weight: 700;
            color: #2c3e50;
            border: none;
            padding: 18px 15px;
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .table td {
            padding: 15px;
            border-color: #f1f3f4;
            vertical-align: middle;
            font-size: 0.9rem;
        }

        .table-striped > tbody > tr:nth-of-type(odd) > td {
            background-color: rgba(52, 152, 219, 0.02);
        }

        .table-hover > tbody > tr:hover > td {
            background-color: rgba(52, 152, 219, 0.05);
            transition: all 0.3s ease;
        }

        .no-data {
            text-align: center;
            padding: 80px 20px;
            color: #6c757d;
            background: white;
            border-radius: 20px;
            box-shadow: 0 8px 30px rgba(0,0,0,0.1);
        }

        .no-data i {
            font-size: 4rem;
            color: #dee2e6;
            margin-bottom: 20px;
        }

        .loading {
            text-align: center;
            padding: 80px 20px;
            background: white;
            border-radius: 20px;
            box-shadow: 0 8px 30px rgba(0,0,0,0.1);
        }

        .loading .spinner-border {
            width: 3rem;
            height: 3rem;
            border-width: 0.3em;
        }

        .loading p {
            margin-top: 20px;
            color: #6c757d;
            font-weight: 500;
        }

        @media (max-width: 768px) {
            .header h2 {
                font-size: 1.8rem;
            }
            
            .filter-card .card-body {
                padding: 20px;
            }
            
            .table-responsive {
                border-radius: 15px;
            }
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">
                <i class="bi bi-database"></i> 提交数据管理
            </a>
            <div class="ms-auto me-0">
                <span id="userInfo" class="me-3 text-white fw-bold"></span>
                <a href="project-management.html" class="btn btn-outline-info btn-sm me-2">
                    <i class="bi bi-folder2-open"></i> 项目管理
                </a>
                <a href="admin-config.html" id="admin-config-btn" class="btn btn-outline-primary btn-sm me-2" style="display: none;">
                    <i class="bi bi-gear"></i> 管理员配置
                </a>
                <button id="logoutBtn" class="btn btn-outline-light">
                    <i class="bi bi-box-arrow-right"></i> 退出登录
                </button>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="header">
            <!-- 在标题右侧新增导出按钮 -->
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h2><i class="bi bi-table"></i> 数据管理中心</h2>
                    <p class="text-muted mb-0">查看和管理所有项目的提交数据，支持多维度筛选和分析</p>
                </div>
                <div class="d-flex align-items-center">
                    <button id="downloadBtn" class="btn btn-outline-primary">
                        <i class="bi bi-download me-2"></i>导出Excel
                    </button>
                </div>
            </div>
        </div>
        
        <div class="filter-card card">
            <div class="card-header">
                <i class="bi bi-funnel me-2"></i>数据筛选器
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4">
                        <label for="projectSelect" class="form-label">
                            <i class="bi bi-folder me-1"></i>项目筛选
                        </label>
                        <select id="projectSelect" class="form-select">
                            <option value="all">所有项目</option>
                            <!-- 项目选项将通过JavaScript动态添加 -->
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label for="recommenderSelect" class="form-label">
                            <i class="bi bi-person-check me-1"></i>业务员筛选
                        </label>
                        <select id="recommenderSelect" class="form-select">
                            <option value="all">所有业务员</option>
                            <!-- <option value="direct">直接访问</option> -->
                            <!-- 管理员选项将通过JavaScript动态添加 -->
                        </select>
                    </div>
                    <div class="col-md-4 d-flex align-items-end">
                        <button id="resetFiltersBtn" class="btn btn-outline-secondary w-100">
                            <i class="bi bi-arrow-clockwise me-2"></i>重置筛选
                        </button>
                    </div>
                </div>
            </div>
        </div>
        
        <div id="loading" class="loading">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p><i class="bi bi-hourglass-split me-2"></i>正在加载数据，请稍候...</p>
        </div>
        
        <div id="submissionsContainer" class="data-card">
            <div class="table-responsive">
                <table id="submissionsTable" class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th><i class="bi bi-person me-1"></i>姓名</th>
                            <th><i class="bi bi-telephone me-1"></i>联系电话</th>
                            <th><i class="bi bi-building me-1"></i>企业名称</th>
                            <th><i class="bi bi-people me-1"></i>参加人员</th>
                            <th><i class="bi bi-geo-alt me-1"></i>地区</th>
                            <th><i class="bi bi-briefcase me-1"></i>行业</th>
                            <th><i class="bi bi-chat-text me-1"></i>留言内容</th>
                            <th><i class="bi bi-clock me-1"></i>提交时间</th>
                            <th><i class="bi bi-folder me-1"></i>项目</th>
                        </tr>
                    </thead>
                    <tbody id="submissionsTableBody">
                        <!-- 提交数据将通过JavaScript动态添加 -->
                    </tbody>
                </table>
            </div>
        </div>
        
        <div id="noData" class="no-data" style="display: none;">
            <i class="bi bi-inbox"></i>
            <h4 class="mt-3 mb-2">暂无提交数据</h4>
            <p class="text-muted">当前筛选条件下没有找到相关数据，请尝试调整筛选条件</p>
        </div>
    </div>



    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" defer></script>
    <script>
        // 检查登录状态
        function checkAuth() {
            const token = localStorage.getItem('token');
            if (!token) {
                window.location.href = '/pages/login.html';
                return false;
            }
            return token;
        }

        // 获取用户信息
        async function getUserInfo() {
            const token = checkAuth();
            if (!token) return;
            
            try {
                const response = await fetch('/users/profile', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    const userData = await response.json();
                    document.getElementById('userInfo').textContent = `${userData.username} (级别: ${userData.level})`;
                    
                    // 如果是系统管理员(级别1)，显示管理员配置按钮
                    if (userData.level === 1) {
                        document.getElementById('admin-config-btn').style.display = 'inline-block';
                    }
                    
                    return userData;
                } else {
                    localStorage.removeItem('token');
                    window.location.href = '/pages/login.html';
                }
            } catch (error) {
                console.error('获取用户信息失败:', error);
            }
        }

        // 加载项目列表
        async function loadProjects() {
            const token = checkAuth();
            if (!token) return;
            
            try {
                const response = await fetch('/projects', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    const projects = await response.json();
                    const projectSelect = document.getElementById('projectSelect');
                    
                    projects.forEach(project => {
                        const option = document.createElement('option');
                        option.value = project.id;
                        option.textContent = project.name;
                        projectSelect.appendChild(option);
                    });
                    
                    // 初始加载所有提交数据
                    loadSubmissions();
                }
            } catch (error) {
                console.error('加载项目失败:', error);
            }
        }

        // 加载管理员列表
        async function loadAdmins() {
            const token = checkAuth();
            if (!token) return;
            
            try {
                const response = await fetch('/users/admins/list', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    const admins = await response.json();
                    const recommenderSelect = document.getElementById('recommenderSelect');
                    
                    admins.forEach(admin => {
                        const option = document.createElement('option');
                        option.value = admin.id;
                        option.textContent = `${admin.username} (级别: ${admin.level})`;
                        recommenderSelect.appendChild(option);
                    });
                }
            } catch (error) {
                console.error('加载管理员列表失败:', error);
            }
        }

        // 加载提交数据 - 优化版本
        let loadSubmissions = async function() {
            const token = checkAuth();
            if (!token) return;
            
            document.getElementById('loading').style.display = 'block';
            document.getElementById('submissionsContainer').style.display = 'none';
            document.getElementById('noData').style.display = 'none';
            
            try {
                const projectId = document.getElementById('projectSelect').value;
                const recommenderId = document.getElementById('recommenderSelect').value;
                
                let url = '/submissions/filter';
                const params = new URLSearchParams();
                
                if (projectId !== 'all') {
                    params.append('projectId', projectId);
                }
                
                if (recommenderId !== 'all') {
                    if (recommenderId === 'direct') {
                        // 对于直接访问，我们需要特殊处理
                        // 这里暂时跳过，因为需要后端支持查询没有推荐管理员的数据
                    } else {
                        params.append('recommenderId', recommenderId);
                    }
                }
                
                if (params.toString()) {
                    url += '?' + params.toString();
                }
                
                // 使用缓存的fetch方法
                const response = await apiCache.fetch(url, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    let submissions = await response.json();
                    
                    // 如果选择了"直接访问"，过滤出没有推荐管理员的数据
                    if (recommenderId === 'direct') {
                        submissions = submissions.filter(submission => !submission.recommendedBy);
                    }
                    
                    // 获取表单配置
                    let formConfig = null;
                    if (projectId !== 'all' && submissions.length > 0) {
                        const project = submissions[0].project;
                        if (project.formConfig) {
                            formConfig = project.formConfig;
                        }
                    }
                    
                    // 动态生成表格头
                    await generateTableHeader(formConfig);
                    
                    const tableBody = document.getElementById('submissionsTableBody');
                    tableBody.innerHTML = '';
                    
                    if (submissions.length === 0) {
                        document.getElementById('noData').style.display = 'block';
                    } else {
                        submissions.forEach(submission => {
                            const row = document.createElement('tr');
                            
                            const data = submission.data;
                            const cells = generateTableCells(data, formConfig, submission.project.name, submission.recommendedBy);
                            row.innerHTML = cells;
                            
                            tableBody.appendChild(row);
                        });
                    }
                }
            } catch (error) {
                console.error('加载提交数据失败:', error);
            } finally {
                document.getElementById('loading').style.display = 'none';
                document.getElementById('submissionsContainer').style.display = 'block';
            }
        };
        // 生成表格头
        async function generateTableHeader(formConfig) {
            const tableHead = document.querySelector('#submissionsTable thead tr');
            tableHead.innerHTML = '';
            
            const defaultFields = {
                name: '姓名',
                phone: '电话',
                company: '公司',
                personnel: '人员规模',
                region: '地区',
                industry: '行业',
                message: '留言内容'
            };
            
            if (formConfig && formConfig.fields) {
                // 根据表单配置显示字段
                Object.keys(defaultFields).forEach(field => {
                    if (formConfig.fields[field]) {
                        const th = document.createElement('th');
                        const label = formConfig.fieldLabels && formConfig.fieldLabels[field] 
                            ? formConfig.fieldLabels[field] 
                            : defaultFields[field];
                        th.textContent = label;
                        tableHead.appendChild(th);
                    }
                });
            } else {
                // 显示所有默认字段
                Object.values(defaultFields).forEach(label => {
                    const th = document.createElement('th');
                    th.textContent = label;
                    tableHead.appendChild(th);
                });
            }
            
            // 添加提交时间、项目名称和推荐管理员列
            const timeHeader = document.createElement('th');
            timeHeader.textContent = '提交时间';
            tableHead.appendChild(timeHeader);
            
            const projectHeader = document.createElement('th');
            projectHeader.textContent = '项目名称';
            tableHead.appendChild(projectHeader);
            
            const referrerHeader = document.createElement('th');
            referrerHeader.textContent = '对接业务员';
            tableHead.appendChild(referrerHeader);
        }
        
        // 生成表格单元格
        function generateTableCells(data, formConfig, projectName, referredBy) {
            const defaultFields = ['name', 'phone', 'company', 'personnel', 'region', 'industry', 'message'];
            let cells = '';
            
            if (formConfig && formConfig.fields) {
                // 根据表单配置显示字段
                defaultFields.forEach(field => {
                    if (formConfig.fields[field]) {
                        cells += `<td>${data[field] || '-'}</td>`;
                    }
                });
            } else {
                // 显示所有默认字段
                defaultFields.forEach(field => {
                    cells += `<td>${data[field] || '-'}</td>`;
                });
            }
            
            // 添加提交时间、项目名称和推荐管理员
            cells += `<td>${new Date(data.submittedAt).toLocaleString()}</td>`;
            cells += `<td>${projectName || '-'}</td>`;
            cells += `<td>${referredBy ? referredBy.username : '直接访问'}</td>`;
            
            return cells;
        }



        // 项目选择变更事件
        document.getElementById('projectSelect').addEventListener('change', function() {
            loadSubmissions();
        });

        // 推荐管理员选择变更事件
        document.getElementById('recommenderSelect').addEventListener('change', function() {
            loadSubmissions();
        });

        // 重置筛选按钮点击事件
        document.getElementById('resetFiltersBtn').addEventListener('click', function() {
            document.getElementById('projectSelect').value = 'all';
            document.getElementById('recommenderSelect').value = 'all';
            loadSubmissions();
        });



        // 退出登录
        document.getElementById('logoutBtn').addEventListener('click', function() {
            localStorage.removeItem('token');
            window.location.href = '/pages/login.html';
        });

        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', async function() {
            const token = checkAuth();
            if (token) {
                // 使用防抖包装，确保依赖的api-cache.js已加载
                loadSubmissions = debounce(loadSubmissions, 300);
                await getUserInfo();
                await loadProjects();
                await loadAdmins();
            }
        });

        // 导出当前表格为 Excel（.xlsx）
        function downloadTableAsExcel() {
            const table = document.getElementById('submissionsTable');
            const headerCells = Array.from(table.querySelectorAll('thead th'));
            const bodyRows = Array.from(table.querySelectorAll('tbody tr'));
            const tbody = document.getElementById('submissionsTableBody');

            if (!tbody || tbody.children.length === 0) {
                alert('暂无数据可导出');
                return;
            }

            const headers = headerCells.map(th => th.innerText.trim());
            const dataRows = bodyRows.map(tr => Array.from(tr.querySelectorAll('td')).map(td => td.innerText.trim()));
            const aoa = [headers, ...dataRows];

            const ws = XLSX.utils.aoa_to_sheet(aoa);
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, 'Submissions');

            const now = new Date();
            const pad = (n) => String(n).padStart(2, '0');
            const filename = `submissions_${now.getFullYear()}${pad(now.getMonth()+1)}${pad(now.getDate())}_${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}.xlsx`;

            XLSX.writeFile(wb, filename);
        }

        // 绑定导出按钮事件
        (function bindDownloadBtn() {
            const downloadBtn = document.getElementById('downloadBtn');
            if (downloadBtn) {
                downloadBtn.addEventListener('click', downloadTableAsExcel);
            }
        })();
    </script>
    <script>
      if ('serviceWorker' in navigator) {
        window.addEventListener('load', () => {
          navigator.serviceWorker
            .register('/sw.js')
            .catch(err => console.error('SW registration failed:', err));
        });
      }
    </script>
</body>
</html>